package com.bidevalution.business.impl;

import com.bidevalution.business.context.ParamsType;
import com.bidevalution.business.context.SexType;
import com.bidevalution.business.service.BeSectionExpertInfoService;
import com.bidevalution.business.service.BeSectionInfoService;
import com.bidevalution.dao.entity.BeExpertInfo;
import com.bidevalution.dao.entity.BeSectionExpertInfo;
import com.bidevalution.dao.entity.BeSectionInfo;
import com.bidevalution.dao.entity.BeSysParams;
import com.bidevalution.dao.mapper.BeExpertInfoMapper;
import com.bidevalution.dao.mapper.BeSectionExpertInfoDelMapper;
import com.bidevalution.dao.mapper.BeSectionExpertInfoMapper;
import com.bidevalution.dao.mapper.BeSectionExpertProgressMapper;
import com.bidevalution.dao.mapper.BeSysParamsMapper;
import com.bidevalution.service.EntInfoService;
import com.bidevalution.support.context.Constants;
import com.bidevalution.support.exception.BizException;
import com.ggzy.tongyi.dubbo.api.EnterPriseInfoDubboService;
import com.qtp.auth.api.UserRightService;
import com.qtp.auth.api.UserService;
import com.qtp.core.model.Response;
import com.qtp.core.util.DateUtil;
import com.qtp.core.util.IdsUtil;
import com.qtp.core.util.Md5Util;
import com.qtp.core.util.OConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by glodon on 2019-08-08.
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class BeSectionExpertInfoServiceImpl implements BeSectionExpertInfoService {
    @Autowired(required = false)
    private BeSectionExpertInfoMapper beSectionExpertInfoMapper;
 
    @Autowired(required = false)
    private BeSectionExpertInfoDelMapper beSectionExpertInfoDelMapper;
    @Autowired(required = false)
    private BeExpertInfoMapper beExpertInfoMapper;
    @Autowired(required = false)
    private UserService userService;
    @Autowired(required = false)
    private BeSysParamsMapper beSysParamsMapper;
    @Autowired
    private BeSectionExpertProgressMapper beSectionExpertProgressMapper;
    private Logger log = Logger.getLogger(getClass());
    /**
     * 获取专家列表
     * @param sectionId
     * @return
     * @throws Exception
     */
    @Override
    public List<BeSectionExpertInfo> getExpertListBySectionId(String sectionId,String voteType,String submitCode) throws Exception {
        return beSectionExpertInfoMapper.getExpertListBySectionId(sectionId,voteType,submitCode);
    }

    /**
     * 保存专家信息:判断用户系统是否存在
     * @param beSectionExpertInfo
     * @return
     * @throws Exception
     */
    @Override
    public Boolean saveExpertInfo(BeSectionExpertInfo beSectionExpertInfo,String password) throws Exception {
        //身份证号
        String cardNo = beSectionExpertInfo.getCardNo();
        if(beSectionExpertInfoMapper.getSectionExpertInfo(beSectionExpertInfo.getSectionId(),cardNo)!=null){
            throw new Exception("专家信息已存在");
        }
        for(BeSysParams beSysParams: beSysParamsMapper.selectForList(ParamsType.expertSource.name())){
        	if(beSectionExpertInfo.getExpertSource() != null && beSectionExpertInfo.getExpertSource().equals(beSysParams.getSypaValue())) {
                beSectionExpertInfo.setExpertSourceName(beSysParams.getSypaName());
        	}
        }
        beSectionExpertInfo.setExpertCode(getExpertCode(beSectionExpertInfo.getSectionId()));
        if(beSectionExpertInfoMapper.insert(beSectionExpertInfo) != 1){
            throw new Exception("专家信息保存失败");
        }

        //专家基本数据不存在时，进行新增操作
        if(beExpertInfoMapper.selectByCardNo(cardNo) == null) {
            BeExpertInfo beExpertInfo = new BeExpertInfo();
            PropertyUtils.copyProperties(beExpertInfo, beSectionExpertInfo);
            beExpertInfo.setSeqId(IdsUtil.uuid());
            if (beExpertInfoMapper.insert(beExpertInfo) != 1) {
                throw new Exception("专家基本信息保存失败");
            }

            Map<String, Object> map = new HashMap<>();
            map.put("userName", beSectionExpertInfo.getName());
            map.put("userLoginName", beSectionExpertInfo.getLoginName());
            map.put("userPassword", password);
            map.put("orgId", IdsUtil.uuid());
            map.put("orgName", beSectionExpertInfo.getWorkUnit());
            map.put("userSex", SexType.getCodeByName(beExpertInfo.getSex()));
            map.put("userMobile", beSectionExpertInfo.getPhone());
            map.put("roleGuids", "6150348b-8bab-4642-a641-9c39166ebe75");
            map.put("userLoginMethod", Constants.ONE);
            map.put("createUser", "评标专家2.0推送");
            Response registerResponse = userService.registeredUser(map);
            if (registerResponse != null) {
                if (registerResponse.isSuccess()) {
                    return true;
                } else {
                	log.error("专家账号推送失败，失败原因："+registerResponse.getError());
                    throw new Exception("专家账号推送失败，失败原因：" + registerResponse.getError());
                }
            } else {
                throw new Exception("专家账号推送失败");
            }
        }

        return true;
    }
    String getExpertCode(String sectionId) {
    	int size = beSectionExpertInfoMapper.getListBySectionId(sectionId).size();
    	if(size>9) {
    		return DateUtil.getCurrentDateStr("yyMMdd")+size;
    	}else {
    		return DateUtil.getCurrentDateStr("yyMMdd")+"0"+size;
    	}
    }
    /**
     * 删除专家信息
     * @param seqIds
     * @return
     * @throws Exception
     */
    @Override
    public Boolean deleteBeSectionExpertInfos(String seqIds) throws Exception {
        if (OConvertUtils.isNotEmpty(seqIds)) {
            String[] idArr = seqIds.split(",");
            for (String id : idArr) {
                if (beSectionExpertInfoMapper.deleteByPrimaryKey(id) != 1) {
                    throw new Exception("删除失败");
                }
            }
        }
        return true;
    }

    @Override
    public List<BeSectionExpertInfo> getAllExpertListBySectionId(String sectionId) {
        List<BeSectionExpertInfo> infoList =  beSectionExpertInfoMapper.getListBySectionId(sectionId);
        infoList.addAll(beSectionExpertInfoDelMapper.getExpertDelListBySectionId(sectionId));
        return infoList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delBeSectionExpertInfos(String seqIds, String remark) {
        if (OConvertUtils.isNotEmpty(seqIds)) {
            String[] idArr = seqIds.split(",");
            for (String id : idArr) {
                //TODO 1.方欣接口校验时也有删除调用需注意
                beSectionExpertInfoDelMapper.insertDelExpert(id, remark);
                beSectionExpertInfoMapper.deleteByPrimaryKey(id);
            }
        }
    }

    /**
     * 根据身份证号码查询专家基本库信息
     * @param cardNo 身份证号码
     * @return
     * @throws Exception
     */
    @Override
    public BeExpertInfo queryExpertInfoByCardNo(String cardNo) throws Exception {
        return beExpertInfoMapper.selectByCardNo(cardNo);
    }

    /**
     * querySectionExpertInfoById
     * @param seqId 根据主键查询
     * @return
     * @throws Exception
     */
    @Override
    public BeSectionExpertInfo querySectionExpertInfoById(String seqId) throws Exception {
        return beSectionExpertInfoMapper.selectByPrimaryKey(seqId);
    }

    @Override
    public BeSectionExpertInfo selectByLoginName(String sectionId, String loginName) {
        // TODO Auto-generated method stub
        return beSectionExpertInfoMapper.selectByLoginName(sectionId, loginName);
    }

    @Override
    public Boolean updateAvoidReason(BeSectionExpertInfo beSectionExpertInfo) throws Exception {
        if (beSectionExpertInfoMapper.updateAvoidReason(beSectionExpertInfo) > 0) {
            return true;
        }
        return false;
    }

    @Override
    public String isEnterReview(String sectionId, String loginName) throws Exception {
        String flag = Constants.FALSE;
        Map<String, Object> dataMap = beSectionExpertInfoMapper.queryByLoginName(sectionId, loginName);
        if (OConvertUtils.getInt(dataMap.get("isAvoid")) == 0 && OConvertUtils.getInt(dataMap.get("reviewState")) > 1) {
            flag = Constants.TRUE;
        }
        if(beSectionExpertProgressMapper.selectBySectionIdAndExpertId(sectionId, dataMap.get("seqId").toString()).size()==0) {
        	throw new BizException("当前标段评审流程正在同步数据,请稍后再试");
        }
        return flag;
    }

    @Override
    public List<String[]> findMd5ByLoginNames(String sectionId) throws Exception {
        List<String[]> list = new ArrayList<>();
        List<BeSectionExpertInfo> beSectionExpertInfos = beSectionExpertInfoMapper.getListBySectionId(sectionId);
        for (BeSectionExpertInfo beSectionExpertInfo: beSectionExpertInfos) {
//            list.add(new String[]{Md5Util.getMD5(beSectionExpertInfo.getLoginName()).toUpperCase(), beSectionExpertInfo.getSeqId()});
            list.add(new String[]{beSectionExpertInfo.getLoginName(), beSectionExpertInfo.getSeqId()});
        }
        return list;
    }

    @Override
	public List<BeSectionExpertInfo> getAllListBySectionId(String sectionId) throws Exception {

		return beSectionExpertInfoMapper.getListBySectionId(sectionId);
	}

	@Override
	public List<BeSectionExpertInfo> getListBySectionId(String sectionId, String isAvoid) throws Exception {

		return beSectionExpertInfoMapper.getList(sectionId, isAvoid);
	}
}
